package com.winit.common.util;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.base.bean.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * Created by wangjian on 16/1/16.
 */
public class UserInfoUtil {
    static final Logger logger = LoggerFactory.getLogger(UserInfoUtil.class);

    public static LoginUser getUserInfo(String tokenId, String BEETLE_AUTH_URL) {

        if (StringUtils.isEmpty(tokenId)) {
            logger.info("获取用户信息失败,tokenId=null");
            return null;
        }
        if (StringUtils.isEmpty(BEETLE_AUTH_URL)) {
            logger.info("获取用户信息失败,BEETLE_AUTH_URL=null");
            return null;
        }
        LoginUser userInfo = null;
        try {
            JSONObject jsonObject = HttpClientUtil.doGetForJson(BEETLE_AUTH_URL + "/login/info?token_id=" + tokenId);
            if (jsonObject.getBoolean("success")) {
                userInfo = JSONObject.toJavaObject(jsonObject.getJSONObject("data"), LoginUser.class);
            }
        } catch (Exception e) {
            logger.error("com.winit.common.filter.UserInfoUtil.getUserInfo 异常", e);
        }

        if (userInfo == null || StringUtils.isEmpty(userInfo.getUserName()) || userInfo.getUserRole().size() == 0) {
            logger.info("获取用户信息失败,tokenId=" + tokenId + ",userInfo=null");
            return null;
        }

        logger.info("获取用户信息成功,tokenId=" + tokenId + ",userInfo=" + ObjectToString.getString(userInfo));
        userInfo.setTokenId(tokenId);
        return userInfo;
    }
}
